<template>
  <div>
    <!-- 三级分类 -->
    <el-card class="box-card">
      <el-form class="ml-20" label-width="80px" inline :disabled="isAdd">
        <el-form-item label="一级分类">
          <el-select
            style="width: 250px"
            v-model="category.category1Id"
            placeholder="请选择"
            @change="getCategory2List"
          >
            <el-option
              v-for="c1 in category1List"
              :key="c1.id"
              :label="c1.name"
              :value="c1.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="二级分类">
          <el-select
            style="width: 250px"
            v-model="$store.state.category.category2Id"
            placeholder="请选择"
            @change="getCategory3List"
          >
            <el-option
              v-for="c2 in category2List"
              :key="c2.id"
              :label="c2.name"
              :value="c2.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="三级分类">
          <el-select
            style="width: 250px"
            v-model="$store.state.category.category3Id"
            placeholder="请选择"
            @change="changeCategory3Id"
          >
            <el-option
              v-for="c3 in category3List"
              :key="c3.id"
              :label="c3.name"
              :value="c3.id"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 平台属性列表 -->
    <el-card class="box-card">
      <!-- 列表展示区域 -->
      <div v-show="!isAdd">
        <el-button
          class="mb-10"
          icon="el-icon-plus"
          type="primary"
          size="small"
          @click="isAdd = true"
          :disabled="!category.category3Id"
          >添加属性</el-button
        >
        <el-table :data="attrList" border style="width: 100%">
          <el-table-column label="序号" type="index" width="80" align="center">
          </el-table-column>
          <el-table-column label="属性值" width="160" prop="attrName">
          </el-table-column>
          <el-table-column label="属性值列表" prop="name">
            <template #default="{ row }">
              <el-tag
                size="small"
                class="mr-5"
                type="success"
                v-for="attrVal in row.attrValueList"
                :key="attrVal.id"
                >{{ attrVal.valueName }}</el-tag
              >
            </template>
          </el-table-column>
          <el-table-column label="操作" width="160" prop="address">
            <template #default="{ row }">
              <el-button
                icon="el-icon-edit-outline"
                type="warning"
                size="small"
                @click="editAttr(row)"
              ></el-button>
              <el-popconfirm
                :title="`确定删除[${row.attrName}]属性吗？`"
                @onConfirm="deleteAttr(row)"
              >
                <el-button
                  slot="reference"
                  icon="el-icon-delete"
                  type="danger"
                  size="small"
                ></el-button>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 新增属性区域 -->
      <div v-show="isAdd">
        <el-form :inline="true">
          <el-form-item label="属性名">
            <el-input
              v-model="attrForm.attrName"
              type="text"
              placeholder="输入属性名"
            ></el-input>
          </el-form-item>
        </el-form>

        <div class="mb-10">
          <el-button
            type="primary"
            :disabled="!attrForm.attrName"
            @click="addAttrVal"
            >添加属性值</el-button
          >
          <el-button @click="cancelSave">取消</el-button>
        </div>

        <el-table :data="attrForm.attrValueList" class="mb-10" border>
          <el-table-column
            type="index"
            label="序号"
            align="center"
            width="80"
          ></el-table-column>
          <el-table-column label="属性值名称">
            <template #default="{ row, $index }">
              <el-input
                v-if="row.inputVisible"
                v-model="row.valueName"
                ref="inputRef"
                @blur="inputBlur(row, $index)"
              ></el-input>
              <div v-else @click="inputFocus(row)">{{ row.valueName }}</div>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="80">
            <template #default="{ row, $index }">
              <el-button
                type="danger"
                size="small"
                icon="el-icon-delete"
                @click="deleteAttrVal(row, $index)"
              ></el-button>
            </template>
          </el-table-column>
        </el-table>

        <div>
          <el-button
            type="primary"
            :disabled="!(attrForm.attrName && attrForm.attrValueList.length)"
            @click="onSave"
            >保存</el-button
          >
          <el-button @click="cancelSave">取消</el-button>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script>
import { mapActions, mapState } from "vuex";
import store from "@/store";
import attrApi from "@/api/attr";
import { cloneDeep } from "lodash";
export default {
  name: "Attr",
  data() {
    return {
      // 存储store的category命名空间,引入的store需要现在data中使用一下才行
      /* 
        使用store的两种方式
          一种是引入store,在data中使用下
          第二种是使用$store
      */
      category: store.state.category,
      attrList: [],
      // 控制添加还是列表展示的开关
      isAdd: false,
      // 用于存放添加属性是的表单数据
      attrForm: {
        attrName: "",
        attrValueList: [],
        categoryId: undefined, // 点击保存按钮执行回调的时候再去赋这个值
        categoryLevel: 3, // 写死
      },
    };
  },
  methods: {
    ...mapActions("category", [
      "getCategory1List",
      "getCategory2List",
      "getCategory3List",
    ]),
    // 改变三级分类后触发的回调
    async changeCategory3Id() {
      const { category1Id, category2Id, category3Id } = this.category;
      try {
        let result = await attrApi.getAttrListInfo(
          category1Id,
          category2Id,
          category3Id
        );
        this.attrList = result.data;
      } catch (error) {
        this.$message.error("获取平台属性失败，请重试");
      }
    },

    //#region
    // 初始化平台属性表单数据的函数
    // 初始化 attrForm
    // initAttrForm: () => ({
    //   attrName: "",
    //   attrValueList: [],
    //   categoryId: undefined, // 点击保存按钮执行回调的时候再去赋这个值
    //   categoryLevel: 3, // 写死
    // }),
    //#endregion

    // 删除平台属性的回调
    async deleteAttr(row) {
      try {
        let result = await attrApi.deleteAttr(row.id);
        console.log("删除的结果", result);
        this.$message.success("删除成功");
        // 刷新页面
        this.changeCategory3Id();
      } catch (error) {
        this.$message.error("删除失败请重试");
      }
    },

    // 点击添加属性值的回调
    addAttrVal() {
      this.attrForm.attrValueList.push({
        valueName: "",
        inputVisible: true, // 用来判断是否显示input框
      });
      // 聚焦
      this.$nextTick(() => {
        this.$refs.inputRef.focus();
      });
    },

    // input框失焦的时候触发
    inputBlur(row, index) {
      row.inputVisible = false;

      // 判断输入的数据的是否为空
      if (!row.valueName.trim()) {
        this.attrForm.attrValueList.splice(index, 1);
        this.$message.error("输入的内容不能为空！");
        return;
      }

      // 判断输入的内容是否重复
      const isRepeat = this.attrForm.attrValueList.some((item, idx) => {
        if (index == idx) {
          // 在晒村的额过成功需要排除掉自己
          return false;
        } else {
          return item.valueName === row.valueName;
        }
      });
      if (isRepeat) {
        this.attrForm.attrValueList.splice(index, 1);
        this.$message.error("输入的内容重复，请重新输入");
        return;
      }
    },

    // input框重新聚焦
    inputFocus(row) {
      row.inputVisible = true;
      this.$nextTick(() => {
        this.$refs.inputRef.focus();
      });
    },

    // 保存的回调
    async onSave() {
      this.attrForm.categoryId = this.category.category3Id;
      try {
        let result = await attrApi.saveAttr(this.attrForm);
        // console.log(result);
        this.$message.success("保存成功");

        this.cancelSave();
      } catch (error) {
        this.$message.error("保存失败，请重试");
      }
    },

    // 取消的回调
    cancelSave() {
      this.isAdd = false;
      this.attrForm = {
        attrName: "",
        attrValueList: [],
        categoryId: undefined, // 点击保存按钮执行回调的时候再去赋这个值
        categoryLevel: 3, // 写死
      };
      this.changeCategory3Id();
    },

    // 删除属性值的回调
    deleteAttrVal(row, index) {
      this.attrForm.attrValueList.splice(index, 1);
    },

    // 编辑回调
    editAttr(row) {
      this.isAdd = true; // 切换编辑界面
      this.attrForm = cloneDeep(row); // 回显数据
    },
  },
  computed: {
    ...mapState({
      category1List: (state) => state.category.category1List,
      category2List: (state) => state.category.category2List,
      category3List: (state) => state.category.category3List,
    }),
  },

  mounted() {
    this.getCategory1List();
  },
};
</script>

<style scoped>
.box-card {
  width: 96%;
  margin: 20px;
}
</style>